import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Notify } from "vant";
import { getToken } from "./auth";

export const serverUrl = "http://localhost:1337";
const instance = axios.create({
  baseURL: serverUrl,
  timeout: 5000,

  //如果允许客户端发起ajax请求的时候，传cookie给服务器  使用下面这句话  进行权限验证
  // withCredentials: true,
});

//全局请求拦截   网络请求发起之前执行
// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start();
    config.headers.token = getToken(); //在请求头中设置token  token的添加方式不固定  看接口文档
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

//全局响应拦截   网络请求发起完成之后执行
// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    NProgress.done();
    return response.data;
  },

  //全局网络请求异常处理
  function (error) {
    // console.dir(error);
    if (error.response?.data) {
      Notify({
        type: "danger",
        message:
          error.response.status +
          "|" +
          (error.response.data.message
            ? error.response.data.message
            : error.response.data.info),
      });
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    NProgress.done();
    return Promise.reject(error);
  }
);
export const get = (url, params) => instance.get(url, { params });
export const post = (url, data) => instance.post(url, data);
export const put = (url, data) => instance.put(url, data);
export const del = (url) => instance.delete(url);
